import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:mmkv/mmkv.dart';
import 'package:seedfour/app/models/user_info_entity.dart';

import '../../constants.dart';
import '../../routes/app_routes.dart';
import '../../services/api_service.dart';
import '../web_screen/screen_params.dart';

class SplashLogic extends GetxController {
  final apiService = Get.put(ApiService());

  final mmkv = MMKV.defaultMMKV();

  final agreementUrl = 'https://api.seedfour.com/res/api/v1/user/agreement';
  final privacyUrl = 'https://api.seedfour.com/res/api/v1/user/privacy';

  var showPrivacyDialog = false.obs;

  @override
  void onReady() {
    super.onReady();

    showPrivacyDialog.value = !_checkAgreePrivacy();

    if (_checkAgreePrivacy()) {
      _checkLogin();
    }
  }

  void onPrivacyAgreed() {
    mmkv.encodeBool(kKeyPrivacyAgreed, true);
    _checkLogin();
  }

  void onPrivacyDisagreed() {
    mmkv.encodeBool(kKeyPrivacyAgreed, false);
    SystemNavigator.pop();
  }

  void onClickAgreement() {
    Get.toNamed(RouteGet.webScreen,
        arguments: WebScreenParams(url: agreementUrl));
  }

  void onClickPrivacy() {
    Get.toNamed(RouteGet.webScreen,
        arguments: WebScreenParams(url: privacyUrl));
  }

  void _checkLogin() {
    if (_checkUserLoggedIn()) {
      _checkUserInfo().then((value) {
        if (value) {
          Get.offAllNamed(RouteGet.main);
        } else {
          Get.offAllNamed(RouteGet.login);
        }
      });
    } else {
      Get.offAllNamed(RouteGet.login);
    }
  }

  bool _checkUserLoggedIn() {
    final String? token = mmkv.decodeString(kKeyToken);
    final String? orgId = mmkv.decodeString(kKeyOrgId);

    return token != null &&
        token.isNotEmpty &&
        orgId != null &&
        orgId.isNotEmpty;
  }

  bool _checkAgreePrivacy() {
    return mmkv.decodeBool(kKeyPrivacyAgreed);
  }

  Future<bool> _checkUserInfo() async {
    UserInfoEntity? userInfo = await apiService.getUserInfo();

    if (userInfo != null) {
      return true;
    } else {
      return false;
    }
  }
}
